package cn.kgc.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

/**
 * @author wangyue
 * @version 1.0
 */
@Configuration
public class WxPayConfig {
    /**
     * 私钥文件
     */
    @Value("${wechat.pay.private-key-path}")
    private Resource privateKeyResource;

    /**
     * 商户号
     */
    @Value("${wechat.pay.mch-id}")
    private String mchId;

    /**
     * 秘钥
     */
    @Value("${wechat.pay.api-v3-key}")
    private String apiV3Key;

    /**
     * 证书序列号
     */
    @Value("${wechat.pay.cert-serial-no}")
    private String certSerialNo;

    @Bean
    public HttpClient httpClient() throws Exception {
        // 加载私钥
        PrivateKey privateKey = PemUtil.loadPrivateKey(
                new FileInputStream(privateKeyResource.getFile())
        );

        // 构建签名验证器
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(mchId, new PrivateKeySigner(certSerialNo, privateKey)),
                apiV3Key.getBytes(StandardCharsets.UTF_8)
        );

        return WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, certSerialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

}
